package com.twh.www.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.twh.www.entity.WnAdmin;
import com.twh.www.entity.WnGoods;
import com.twh.www.entity.WnUser;
import com.twh.www.service.*;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AdminController {
    @Autowired
    private MinioService minioService;
    @Autowired
    private WnGoodsService wnGoodsService;
    @Autowired
    private WnCategoryService wnCategoryService;
    @Autowired
    WnAdminService adminService;
    @Autowired
    WnUserService userService;

    @GetMapping("/admin")
    public String admin(HttpSession session) {
        WnUser user = (WnUser) session.getAttribute("LoginUser");

        if (user == null || !user.getRole().equals("admin")) {
            System.out.println("非管理员用户尝试访问后台");
            return "redirect:/"; // 不是管理员，重定向到首页或其他页面
        }
        return "admin";
    }

    @GetMapping("/admin/logout")
    public String adminLogout(HttpSession session) {
        session.removeAttribute("LoginUser");
        return "redirect:/";
    }

    /**
     * 商品图片上传接口，校验格式和大小，上传到MinIO
     */
    @PostMapping("/admin/upload/good")
    @ResponseBody
    public String uploadGoodImage(@RequestParam("file") MultipartFile file) throws Exception {
        // 校验格式
        String fileName = file.getOriginalFilename();
        if (fileName == null || !(fileName.endsWith(".jpg") || fileName.endsWith(".png"))) {
            return "图片格式仅支持jpg/png";
        }
        // 校验大小
        if (file.getSize() > 5 * 1024 * 1024) {
            return "图片大小不能超过2M";
        }
        // 上传到MinIO
        String imageUrl = minioService.uploadFile(file);
        return imageUrl;
    }

    @GetMapping("/admin/goods/add")
    public String addGoods(Model model) {
        model.addAttribute("categories", wnCategoryService.list());
        return "goods_add";
    }

    @PostMapping("/admin/goods/add")
    public String addGoods(
            @RequestParam("name") String name,
            @RequestParam("no") String no,
            @RequestParam("categoryId") Integer categoryId,
            @RequestParam("stock") Integer stock,
            @RequestParam("marketPrice") BigDecimal marketPrice,
            @RequestParam("salePrice") BigDecimal salePrice,
            @RequestParam("imageUrl") String imageUrl,
            @RequestParam("description") String description,
            @RequestParam(value = "hottest", required = false) String hottest,
            @RequestParam(value = "newest", required = false) String newest
    ) {
        WnGoods goods = new WnGoods();
        goods.setName(name);
        goods.setNo(no);
        goods.setCategoryId(categoryId);
        goods.setStock(stock);
        goods.setMarketPrice(marketPrice);
        goods.setSalePrice(salePrice);
        goods.setImage(imageUrl);
        goods.setDescription(description);
        goods.setHottest("y".equalsIgnoreCase(hottest) ? "Y" : "N");
        goods.setNewest("y".equalsIgnoreCase(newest) ? "Y" : "N");
        goods.setStatus("Y"); // 正常上架
        goods.setSaleTime(LocalDateTime.now());
        wnGoodsService.save(goods);
        return "redirect:/";
    }


    @GetMapping("/admin/category/add")
    public String addCategory() {
        return "category_add";
    }


    @GetMapping("/admin/goods/list")
    public String listGoods(@RequestParam(defaultValue = "1") int adminPage,
                            @RequestParam(defaultValue = "10") int pagesSize,
                            Model model) {
        Page<WnGoods> goodsPages = wnGoodsService.getadminGoodsByPage(adminPage, pagesSize);
        model.addAttribute("goodsPages", goodsPages);
        model.addAttribute("currentPages", adminPage);
        model.addAttribute("totalPagess", goodsPages.getPages());
        return "goodsList";
    }




    @GetMapping("/admin/user/list")
    public String listUser(Model model) {
        List<WnUser> userlist = adminService.getAllUser();
        model.addAttribute("userlist", userlist);
        return "admin_list";
    }

    @GetMapping("/admin/manager/list")
    public String listadmin(Model model) {
        List<WnAdmin> managerList = adminService.getAllAdmin();
        // 标记已删除的管理员
        for (WnAdmin admin : managerList) {
            if ("4".equals(admin.getStatus())) {
                admin.setAccount(admin.getAccount() + " (已删除)"); // 可以通过修改其他属性或添加新属性来标记
            }
        }
        model.addAttribute("managerList", managerList);
        return "admin_manager_list";
    }

    @GetMapping("/admin/user/freeze")
    public String freezeUser(@RequestParam Integer id) {
        boolean success = userService.freezeUser(id);
        return "redirect:/admin/user/list";
    }

    @GetMapping("/admin/user/unfreeze")
    public String unfreezeUser(@RequestParam Integer id) {
        boolean success = userService.unfreezeUser(id);
        return "redirect:/admin/user/list";
    }

    @GetMapping("/admin/user/blacklist/add")
    public String addToBlacklistUser(@RequestParam Integer id) {
        boolean success = userService.addToBlacklist(id);
        return "redirect:/admin/user/list";
    }

    @GetMapping("/admin/user/blacklist/remove")
    public String removeFromBlacklistUser(@RequestParam Integer id) {
        boolean success = userService.removeFromBlacklist(id);
        return "redirect:/admin/user/list";
    }

    @GetMapping("/admin/user/delete")
    public String deleteUser(@RequestParam Integer id) {
        boolean success = userService.deleteUser(id);
        return "redirect:/admin/user/list";
    }

    // 管理员冻结
    @GetMapping("/admin/manager/freeze")
    public String freezeAdmin(@RequestParam Integer id) {
        boolean success = adminService.freezeAdmin(id);
        return "redirect:/admin/manager/list";
    }

    // 管理员解冻
    @GetMapping("/admin/manager/unfreeze")
    public String unfreezeAdmin(@RequestParam Integer id) {
        boolean success = adminService.unfreezeAdmin(id);
        return "redirect:/admin/manager/list";
    }

    // 管理员加入黑名单
    @GetMapping("/admin/manager/blacklist/add")
    public String addToBlacklistAdmin(@RequestParam Integer id) {
        boolean success = adminService.addToBlacklistAdmin(id);
        return "redirect:/admin/manager/list";
    }

    // 管理员移除黑名单
    @GetMapping("/admin/manager/blacklist/remove")
    public String removeFromBlacklistAdmin(@RequestParam Integer id) {
        boolean success = adminService.removeFromBlacklistAdmin(id);
        return "redirect:/admin/manager/list";
    }

    // 管理员删除
    @GetMapping("/admin/manager/delete")
    public String deleteAdmin(@RequestParam Integer id) {
        boolean success = adminService.deleteAdmin(id);
        return "redirect:/admin/manager/list";
    }

    @GetMapping("/admin/profile/edit")
    public String editAdminProfile(HttpSession session, Model model) {
        WnUser loginUser = (WnUser) session.getAttribute("LoginUser");
        if (loginUser != null && "admin".equals(loginUser.getRole())) {
            // 这里为了在页面上显示管理员信息，我们可能需要从数据库中查询更详细的 WnAdmin 信息
            WnAdmin adminInfo = adminService.getAdminByAccount(loginUser.getAccount());
            model.addAttribute("LoginUser", adminInfo); // 注意这里使用了 "LoginUser" 保持前端一致
            return "admin_profile_edit";
        }
        return "redirect:/"; // 或者其他未授权页面
    }

    @PostMapping("/admin/profile/update")
    @ResponseBody
    public String updateAdminProfile(@RequestParam String account,
                                     @RequestParam(required = false) String password,
                                     @RequestParam(required = false) String repassword,
                                     HttpSession session) {
        WnUser loginUser = (WnUser) session.getAttribute("LoginUser");
        if (loginUser != null && "admin".equals(loginUser.getRole())) {
            WnAdmin admin = adminService.getAdminByAccount(loginUser.getAccount());
            if (admin == null) {
                return "账户信息异常，请重新登录";
            }

            boolean accountUpdated = false;
            boolean passwordUpdated = false;

            if (!account.equals(admin.getAccount())) {
                admin.setAccount(account);
                accountUpdated = adminService.updateAdminAccount(admin);
            }

            if (password != null && !password.isEmpty()) {
                if (!password.equals(repassword)) {
                    return "两次输入的密码不一致！";
                }
                admin.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
                passwordUpdated = adminService.updateAdminPassword(admin);
            }

            if (accountUpdated || passwordUpdated) {
                if (passwordUpdated) {
                    // 如果密码被修改，清除 Session 并重定向到登录页面
                    session.invalidate();
                    return "redirect:/"; // 返回重定向指令
                } else {
                    // 如果只有账号被修改，可以更新 Session 并返回成功
                    WnAdmin updatedAdmin = adminService.getAdminByAccount(account);
                    session.setAttribute("LoginUser", updatedAdmin);
                    return "success";
                }
            } else {
                return "信息未修改";
            }
        }
        return "未授权操作";
    }


    @PostMapping("/admin/goods/updateStock")
    @ResponseBody
    public Map<String, Object> updateStock(@RequestParam Integer id, @RequestParam Integer quantity) {
        Map<String, Object> response = new HashMap<>();
        boolean success = wnGoodsService.updateGoodsStock(id, quantity);
        if (success) {
            response.put("success", true);
        } else {
            response.put("success", false);
            response.put("message", "更新库存失败");
        }
        return response;
    }

    @GetMapping("/admin/goods/delete")
    public String deleteGoods(@RequestParam Integer id) {
        boolean success = wnGoodsService.deleteGoodsById(id);
        return "redirect:/admin/goods/list";
    }



    @GetMapping("/admin/manager/add")
    public String addManagerPage() {
        return "admin_manager_add";
    }

    @PostMapping("/admin/manager/save")
    public String saveManager(@RequestParam String account, @RequestParam String password, Model model) {
        if (account == null || account.length() < 2 || account.length() > 10) {
            model.addAttribute("errorMessage", "账号长度必须在 2 到 10 位之间");
            return "admin_manager_add";
        }
        if (password == null || password.isEmpty()) {
            model.addAttribute("errorMessage", "密码不能为空");
            return "admin_manager_add";
        }

        WnAdmin newAdmin = new WnAdmin();
        newAdmin.setAccount(account);
        newAdmin.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        newAdmin.setStatus("0"); // 默认状态为 0 (正常)

        boolean success = adminService.save(newAdmin);
        if (success) {
            return "redirect:/admin/manager/list";
        } else {
            model.addAttribute("errorMessage", "添加管理员失败，可能账号已存在");
            return "admin_manager_add";
        }
    }
}
